package worldutils.huntgame.Utils;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Chest;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import worldutils.huntgame.HuntGame;
import worldutils.huntgame.Listener.AirDropSet;

import javax.xml.stream.Location;
import java.util.Random;

public class AirDropUtils {
    public static Location getAirDropLoc(){
        int range = HuntGame.AirDropR;
        int randomNumber = getRandomInRange(-range, range);
        int RandomX = getRandomInRange(-range, range);
        int RandomZ = getRandomInRange(-range, range);
        int HighY = getHighY(RandomX,RandomZ);
        Location AirDropLoc = (Location) new org.bukkit.Location(Bukkit.getWorld("world"),RandomX,HighY,RandomZ);
        return AirDropLoc;
    }

    public static int getRandomInRange(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    public static int getHighY(int x, int z) {
        World world = Bukkit.getWorld("world");
        if (world == null) {
            return -1;
        }
        for (int y = world.getMaxHeight(); y >= 0; y--) {
            if (!world.getBlockAt(x, y, z).equals(Material.AIR)) {
                return y;
            }
        }
        return -1;
    }

    public static void setChestatLOC(org.bukkit.Location loc){
//        PlayerUtils.sendMessageToAllPlayer("set1");
        loc.getBlock().setType(Material.CHEST);
//        PlayerUtils.sendMessageToAllPlayer("set2");
        Chest AirDropChest = (Chest) loc.getBlock().getState();
//        PlayerUtils.sendMessageToAllPlayer("set3");
        AirDropChest.getInventory().setContents(AirDropSet.jsonToInventory(HuntGame.AirDropChestNR).getContents());
    }

    public static void summonRandomAirDrop(){
//        PlayerUtils.sendMessageToAllPlayer("sum1");
        org.bukkit.Location loc = RandomSpawnUtils.getRandomLocation(Bukkit.getWorld("world"), 0,0);
//        PlayerUtils.sendMessageToAllPlayer("sum2");
        setChestatLOC(loc);
//        PlayerUtils.sendMessageToAllPlayer("sum3");
        PlayerUtils.sendMessageToAllPlayer("AirDrop已设置在 " + String.valueOf(((int) loc.getX()) + " " + String.valueOf((int) loc.getY()) + " " + String.valueOf((int) loc.getZ())));
    }
}
